package com.td.core.communication;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class Communication {

	private Socket socket;
	
	private Sender sender;
	private Reciever reciever;
	
	public Communication(Socket s, MainReciever mr) throws IOException {
		socket = s;
		sender = new Sender(socket);
		reciever = new Reciever(socket, mr);
	}
	
	public Communication(String host, int port, MainReciever mr) throws UnknownHostException, IOException {
		socket = new Socket (host, port);
		sender = new Sender(socket);
		reciever = new Reciever(socket, mr);
	}
	
	public void send(Sendable<?> obj) {
		sender.send(obj);
	}

	public void start() {
		sender.start();
		reciever.start();
	}

	public void end() {
		sender.interrupt();
		reciever.interrupt();
		try {
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			socket = null;
		}
	}
	
	public boolean isConnected() {
		return socket != null && !socket.isClosed();
	}
}
